import compose from './compose';

// 返回一个store对象
function applyMiddleware(...middlewares) {
  return (createStore) => (reducer, preState) => {
    const store = createStore(reducer, preState);
    let dispatch = store.dispatch;
    let chain = [];

    const middlewareAPI = {
      getState: store.getState,
      dispatch1: action => dispatch(action),
      dispatch: store.dispatch,
    };

    chain = middlewares.map(middleware => {
      console.log(middlewareAPI.dispatch);
      return middleware(middlewareAPI);
    });
    dispatch = compose(...chain)(store.dispatch); // 执行middleware({getState, dispatch}), 更改dispatch
    return {
      ...store,
      dispatch,
    };
  };
}
// 加入middleware只有一个，那个就是fn(store.dispatch)
// 所以中间件应该是 function middleware(next) { // 因为是action是最后的参数
//  return function(action) {
//    return next(action)
//  }
// }
// }
// fn依次作为dispatch，传到上面
export default applyMiddleware
